package com.itlaoqi.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 倒计时锁踢被适合总分任务，例如多线程计算后的数据汇总。
 *
 */
public class ReetrantLockSample {

    public static int count = 0;
    public static int users = 100;
    public static int downTotal = 50000;
    private static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(users);
        for (int i = 0; i < downTotal; i++) {
            final  int index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    add();
                }
            });
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("下载总数" + count);
        threadPool.shutdown();
    }

    private static void add() {
        reentrantLock.lock();
        try {
            count ++;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }
}
